<template>
  <el-dialog v-model="visible" @close="onClose" width="400px" title="批量新增">
    <el-upload
      style="margin-bottom: 10px"
      ref="upload"
      class="upload-demo"
      :action="`${uploadFileUrl}/api/operation/marCoupon/templateVerify`"
      :limit="1"
      :on-exceed="handleExceed"
      :headers="headers"
      :data="{ couponId: params.couponId }"
      :show-file-list="false"
      :on-change="handleChange"
      :auto-upload="false"
    >
      <template #trigger>
        <div>
          <el-button type="primary" icon="Plus">选择文件</el-button>
        </div>
      </template>
      <el-link
        :disabled="disabled"
        type="primary"
        :underline="false"
        style="margin-left: 10px"
        @click="download"
        >模板下载.xlsx</el-link
      >
    </el-upload>
    <div v-if="type === 'warning'" style="display: flex; align-items: center"
      ><el-icon size="30"><WarningFilled /></el-icon>
      <div style="margin-left: 10px"
        >模板下载->填写数据->选择文件 请勿编辑模板第一行，添加数据从第二行开始，最大10M。</div
      >
    </div>
    <div v-if="type === 'success'" style="display: flex; align-items: center"
      ><el-icon size="30" color="#67C23A"><SuccessFilled /></el-icon>
      <div style="margin-left: 10px">
        <div style="margin-bottom: 10px"
          >校验成功，共{{ params.verifyNum }}条数据，计算重复数据后共{{ params.msg }}个用户。</div
        >
        <div>{{ params.name }}</div>
      </div>
    </div>
    <div v-if="type === 'error'" style="display: flex; align-items: center"
      ><el-icon size="30" color="#F56C6C"><CircleCloseFilled /></el-icon>
      <div style="margin-left: 10px">{{ params.msg }}</div>
    </div>
    <template #footer>
      <el-button @click="handleAction(false)">取消</el-button>
      <el-button
        :loading="submit"
        type="primary"
        :disabled="type !== 'success' || !params.msg"
        @click="handleAction(true)"
      >
        下一步
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { checkTemplateApi, directionalAddApi } from '@/api/marketing/activity'
import { getToken } from '@/utils/auth'
import { genFileId } from 'element-plus'
const visible = ref(false)
const submit = ref(false)

const emit = defineEmits(['close'])

const type = ref('warning')

const params = reactive({
  couponId: '',
  file: [],
  msg: ''
})
const formData = ref(null)

function onClose() {
  params.name = ''
  params.file = []
  params.msg = ''
}
function handleAction(confirm) {
  if (confirm) {
    directionalAddApi(formData.value).then((res) => {
      visible.value = false
      emit('close')
    })
  } else {
    visible.value = false
  }
}
const { proxy } = getCurrentInstance()
const disabled = ref(false)
function download() {
  disabled.value = true
  proxy
    .download('/operation/marCoupon/template', {}, `模板${new Date().getTime()}.xlsx`)
    .then(() => {
      disabled.value = false
    })
    .catch((err) => {
      disabled.value = false
    })
}

const uploadFileUrl = ref(`${import.meta.env.VITE_APP_BASE_API}`) // 上传文件服务器地址
const upload = ref(null)
const headers = ref({ Authorization: 'Bearer ' + getToken() })

const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

function handleChange(file) {
  console.log('file', file)
  // 校检文件类型
  const fileName = file.name.split('.')
  const fileExt = fileName[fileName.length - 1]
  const isTypeOk = ['xlsx'].indexOf(fileExt) >= 0
  if (!isTypeOk) {
    type.value = 'error'
    params.msg = '文件格式错误, 请上传xlsx文件。'
    return
  }
  // 校检文件大小
  const isLt = file.size / 1024 / 1024 < 10
  if (!isLt) {
    ElMessage({
      message: `上传文件大小不能超过10MB!`,
      type: 'error'
    })
    return
  }
  params.name = file.name
  params.file = [file.raw]
  formData.value = new FormData()
  formData.value.append('file', params.file[0])
  formData.value.append('couponId', params.couponId)
  checkTemplateApi(formData.value).then((res) => {
    if (res?.data === null) {
      params.msg = res.msg
      type.value = 'error'
    } else {
      params.verifyNum = res?.data?.verifyNum
      params.msg = res?.data?.clientNum
      type.value = 'success'
    }
  })
}

const init = (id) => {
  type.value = 'warning'
  visible.value = true
  params.couponId = id
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped></style>
